import React, {
  useState,
  useRef,
  useImperativeHandle,
  forwardRef,
} from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  TreeSelect,
  DatePicker,
  Radio,
  Checkbox,
  TimePicker,
  Cascader,
  message,
} from 'antd';
import './index.less';

import IrrButton from '../IrrButton';
// import LocationModal from '../IrrMapModal';
// import ImageUpload from '../IrrImgUpload';
// import IrrChoiceBox from '../IrrChoiceBox';
import { RollbackOutlined } from '@ant-design/icons';

import moment from 'moment';

const { Option } = Select;
const { RangePicker } = TimePicker;

export interface IotFormDataItem {
  renderType?: string; // 表单渲染类型
  title: string; //表单标签
  dataIndex?: string; // 表单Key值
  disabled?: boolean; //是否禁用
  required?: boolean; //是否必填
  render?: Function; //自定义渲染
  extra?: anyObject; //表单额外属性
  dataSource?: any; //选择组件 数据源
  validator?: string; //输入框校验类型 phone-手机号 ｜ email-邮箱 ｜ idCard-身份证 ｜ int-正整数 ｜ noSpecial无特殊字符 ｜ blank空格 ｜ letterOrNum/数字或字母 | _int/整数包括0
  formItemProps?: any; //自定义formItem属性
  isShow?: boolean; //是否显示当前条目
  customSelectOption?: {
    buttonOption?: {
      text?: string;
      onClick?: Function; //点击打开弹窗
      label?: string;
    };
    isInputShow?: boolean;
  }; //自定义选择配置项
  list?: IotFormDataItem[]; // 表单分组
  children?: any;
  multiple?: boolean;
  format?: string;
  formatTime?: string;
  MultiSelect?: boolean; // 是否多选
  everyItemStyle: any;
  itemClass?: string;
}

interface Props {
  children?: any;
  className?: string;
  layout?: string;
  formOption?: anyObject;
  currentRecord?: anyObject;
  onFormListChange?: Function;
  contentFormStyle?: anyObject;
  totolItemProps?: anyObject;
  formDisabled?: boolean;
  formList: IotFormDataItem[];
  resetFormList?: Function;
  onFormListSubmit?: Function;
  afterSetLocation?: Function;
  mapOption?: { [key: string]: string };
  queryAndReset?: {
    queryText?: string;
    resetText?: string;
    queryVisible?: boolean;
    resetVisible?: boolean;
    style?: any;
    className?: string;
  };
  customFooter?: boolean;
  validateFinish?: Function;
  width?: string;
}
const IrrFormList = (props: Props, ref: any) => {
  const irrFormRef = useRef<any>(null);
  const choiceTwoRef = useRef<any>(null);
  const locationModelRef = useRef<any>(null);
  const [resetFlag, setResetFlag] = useState<boolean>(true);
  const {
    className = '',
    resetFormList = () => {},
    layout = 'horizontal',
    formOption = {},
    children,
    contentFormStyle = {},
    totolItemProps = {},
    formList = [],
    queryAndReset = {
      queryText: '确认',
      resetText: '取消',
      queryVisible: true,
      resetVisible: true,
      style: {},
      className: '',
    },
    customFooter = false,
  } = props;

  useImperativeHandle(ref, () => {
    return {
      customValidate,
      resetForm,
      customSetForm,
      getFormListValues,
      resetFormFields,
      queryPointInfo,
      getSingleValue,
    };
  });

  const renderFormItem = (item: any, index: number) => {
    const { currentRecord = {}, formDisabled = false } = props;
    const {
      extra = {
        maxLength: 30,
      },
      required = false,
      MultiSelect = false,
      disabled = formDisabled,
      dataSource = [],
      dataIndex,
      title,
      titleStr,
      formatTime,
      renderType,
      formItemProps,
      customSelectOption = {
        buttonOption: {
          text: '点击选择',
          label: '',
        },
        isInputShow: true,
        isStyle: false,
        onClick: () => {},
      },
    } = item;
    const formItemExtra: any = {
      label: title,
      name: dataIndex,
      className: 'irr-form-item',
      ...formItemProps,
    };
    if (item.render) {
      return item.render();
    }
    if (renderType === 'input') {
      return (
        <Form.Item
          rules={
            item?.customValidator?.flag
              ? item.customValidator?.handleValidator
              : buildInputRule(item)
          }
          {...formItemExtra}
          getValueFromEvent={(event) => {
            let value = event.target.value;
            if (extra && Object.keys(extra).length > 0) {
              if (extra.type === 'number') {
                value = value.slice(0, extra.maxLength);
              }
            }
            return value;
          }}
        >
          <Input
            placeholder={`请输入${titleStr || title}`}
            disabled={disabled}
            {...extra}
          />
        </Form.Item>
      );
    } else if (renderType === 'select') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Select
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            optionFilterProp="label"
            showSearch={dataSource?.length > 8}
            allowClear={required ? false : true}
            {...extra}
          >
            {dataSource.map((it: any) => {
              return (
                <Option key={it.value} value={it.value} disabled={it.disabled}>
                  {it.label}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
      );
    } else if (renderType === 'textarea') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Input.TextArea
            placeholder={`请输入${titleStr || title}`}
            disabled={disabled}
            {...extra}
            maxLength={300}
          />
        </Form.Item>
      );
    } else if (renderType === 'treeSelect') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <TreeSelect
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            treeDefaultExpandAll
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={dataSource}
            multiple={MultiSelect}
            disabled={disabled}
            allowClear={required ? false : true}
            {...extra}
          />
        </Form.Item>
      );
    } else if (renderType === 'uploadImage') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择上传${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          {/* <ImageUpload
                        defaultImgUrl={currentRecord[dataIndex]}
                        disabled={disabled}
                        {...extra}
                        getUploadImage={setUploadImage}
                    /> */}
        </Form.Item>
      );
    } else if (renderType === 'choiceTwoBox') {
      return (
        <Form.Item
          rules={[{ required: required, message: `请选择点位` }]}
          {...formItemExtra}
        >
          {/* <IrrChoiceBox {...extra} getUploadImage={setUploadImage} ref={choiceTwoRef} /> */}
        </Form.Item>
      );
    } else if (renderType === 'location') {
      return (
        <div className="location_content__box">
          <div className="location__content">
            <Form.Item rules={buildlocationRule(item)} {...formItemExtra}>
              <Input
                disabled={true}
                placeholder={`请选择${titleStr || title}`}
              />
            </Form.Item>
          </div>
          <div className="location__action_btn">
            <IrrButton
              onClick={() => {
                handleMapOpen(item);
              }}
              style={{ marginTop: 30 }}
              {...extra}
            >
              定位
            </IrrButton>
          </div>
        </div>
      );
    } else if (renderType === 'datePicker') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <DatePicker
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            disabledDate={disabledDate}
            {...extra}
            allowClear={required ? false : true}
          />
        </Form.Item>
      );
    } else if (renderType === 'timePicker') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <TimePicker
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            {...extra}
            format={formatTime}
            allowClear={required ? false : true}
          />
        </Form.Item>
      );
    } else if (renderType === 'rangePicker') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请输入${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <RangePicker
            style={{ width: '100%' }}
            disabled={disabled}
            {...extra}
            format={formatTime}
            allowClear={required ? false : true}
          />
        </Form.Item>
      );
    } else if (renderType === 'radio') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Radio.Group disabled={disabled}>
            {dataSource.map((item: any, index: number) => {
              return (
                <Radio
                  disabled={item.disabled}
                  value={item.value}
                  key={index.toString()}
                  {...extra}
                >
                  {item.label}
                </Radio>
              );
            })}
          </Radio.Group>
        </Form.Item>
      );
    } else if (renderType === 'checkbox') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Checkbox.Group disabled={disabled}>
            <div className="checkbox-group">
              <div className="checkbox-list">
                {dataSource.map((item: any, index: number) => {
                  return (
                    <Checkbox
                      className="checkbox-item"
                      key={index}
                      value={item.value}
                    >
                      {item.label}
                    </Checkbox>
                  );
                })}
              </div>
            </div>
          </Checkbox.Group>
        </Form.Item>
      );
    } else if (renderType === 'Cascader') {
      return (
        <Form.Item
          rules={[
            { required: required, message: `请选择${titleStr || title}` },
          ]}
          {...formItemExtra}
        >
          <Cascader
            style={{ width: '100%' }}
            placeholder={`请选择${titleStr || title}`}
            disabled={disabled}
            options={dataSource}
            {...extra}
          />
        </Form.Item>
      );
    }
  };
  const disabledDate = (current: any) => {
    return current && current >= moment().endOf('day');
  };
  const buildInputRule = (item: any) => {
    const { validator = '', required, title } = item;
    const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; // 身份证号码校验
    // const phoneReg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/; // 手机号码校验
    const phoneReg = /^(1\d{10})$/;
    const emailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; // 邮箱校验
    const chineseReg = /^[0-9a-zA-Z\u0391-\uFFE5?*]{1,}$/; // 只输入汉字，字母，数字
    const intReg = /(^[1-9]\d*$)/; // 只输入正整数
    const _intReg = /(^[0-9]\d*$)/; // 只输入整数包含0
    const blankReg = /^[^\s]*$/; // 禁止输入空格
    const letterReg = /^[a-z0-9]+$/i; // 只输入数字和字母
    const numberReg = /^(\d*\.)?\d+$/; // 只输入数字
    const validateLetterOrNum = (rule: any, value: any) => {
      return validateRule(rule, value, letterReg, '请输入字母或数字');
    };
    const validateNoSpecial = (rule: any, value: any) => {
      return validateRule(rule, value, chineseReg, '请输入汉字、字母、数字');
    };
    const validateIdCard = (rule: any, value: any) => {
      return validateRule(rule, value, idCardReg, '请输入正确格式的身份证号');
    };
    const validateEmail = (rule: any, value: any) => {
      return validateRule(rule, value, emailReg, '请输入正确格式的邮箱号');
    };
    const validatePhone = (rule: any, value: any) => {
      return validateRule(rule, value, phoneReg, '请输入正确格式的手机号');
    };
    const validateInt = (rule: any, value: any) => {
      return validateRule(rule, value, intReg, '请输入正整数');
    };
    const _validateInt = (rule: any, value: any) => {
      return validateRule(rule, value, _intReg, '请输入整数');
    };
    const validateBlank = (rule: any, value: any) => {
      return validateRule(rule, value, blankReg, '禁止输入空格');
    };
    const validateNumber = (rule: any, value: any) => {
      return validateRule(rule, value, numberReg, '请输入数字');
    };
    const resolve = () => Promise.resolve();
    return [
      { required: required, message: `请输入${title}` },
      {
        validator: validator === 'blank' ? validateBlank : resolve,
      },
      {
        validator: validator === 'noSpecial' ? validateNoSpecial : resolve,
      },
      {
        validator: validator === 'idCard' ? validateIdCard : resolve,
      },
      {
        validator: validator === 'email' ? validateEmail : resolve,
      },
      {
        validator: validator === 'phone' ? validatePhone : resolve,
      },
      {
        validator: validator === 'int' ? validateInt : resolve,
      },
      {
        validator: validator === '_int' ? _validateInt : resolve,
      },
      {
        validator: validator === 'letterOrNum' ? validateLetterOrNum : resolve,
      },
      {
        validator: validator === 'number' ? validateNumber : resolve,
      },
    ];
  };

  const buildlocationRule = (item: any) => {
    const { required, title } = item;
    const locationReg =
      /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180),(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/; // 坐标点正则

    const validateLocationReg = (rule: any, value: any) => {
      return validateRule(rule, value, locationReg, `请选择${title}`);
    };

    return [
      { required: required, message: `请选择${title}` },
      {
        validator: validateLocationReg,
      },
    ];
  };

  const validateRule = (rule: any, value: any, reg: any, msg: string) => {
    if (value && !reg.test(value)) {
      return Promise.reject(msg);
    } else {
      return Promise.resolve();
    }
  };

  const customValidate = (cb?: Function) => {
    // const { validateFinish } = props;
    irrFormRef?.current?.validateFields().then(() => {
      const values = irrFormRef?.current?.getFieldsValue(true);
      cb && cb(values);
    });
  };

  const resetForm = () => {
    irrFormRef.current?.resetFields();
  };

  const customSetForm = (values: anyObject) => {
    irrFormRef?.current?.setFieldsValue({ ...values });
  };
  const getFormListValues = (cb?: Function, index?: number) => {
    const values = irrFormRef?.current?.getFieldsValue(true);
    cb && cb(values, index);
  };
  const getSingleValue = (key: string, cb?: Function) => {
    const value = irrFormRef?.current?.getFieldValue(key);
    cb && cb(value);
  };
  const resetFormFields = (cb?: Function, index?: number) => {
    const values = irrFormRef?.current?.getFieldsValue(true);
    // irrFormRef?.current?.resetFields([]);
    irrFormRef.current?.resetFields();
    // cb && cb(values, index);
  };

  const queryPointInfo = (treeList?: any[], areaId?: string) => {
    console.log('queryPointInfo', treeList, 'areaId', areaId);
    choiceTwoRef?.current?.handleGetPointInfo(treeList, areaId);
    // cb && cb(values, index);
  };

  const onFormSubmit = (val: any) => {
    const { onFormListSubmit } = props;
    onFormListSubmit && onFormListSubmit(val);
  };
  const curValuesChange = (curVal: any, totolVal: any, changeType?: string) => {
    const curFlag = [];
    for (let i in totolVal) {
      if (totolVal[i]) {
        curFlag.push(i);
      }
    }
    setResetFlag(curFlag.length === 0);
    const { onFormListChange } = props;
    onFormListChange && onFormListChange(curVal, totolVal, changeType);
  };
  const setUploadImage = (
    fileName: string,
    url: string,
    name: string,
    list: any[],
  ) => {
    const imageObj: any = formList.find(
      (item: any) => item.renderType === 'uploadImage',
    );
    const { dataIndex = '', multiple = false, delimiter } = imageObj;
    let result: any = fileName;
    if (multiple) {
      const arr: string[] = [];
      list.map((item) => {
        arr.push(item.name);
      });
      if (delimiter) {
        result = arr.join(delimiter);
      } else {
        result = arr;
      }
    }
    if (dataIndex) {
      irrFormRef?.current.setFieldsValue({
        [dataIndex]: result,
      });
    }
  };

  const handleMapOpen = (item: any) => {
    const value = irrFormRef?.current?.getFieldValue(item.checkLocation);
    if (item.checkLocation && !value) {
      message.warning('请先选择所属区域');
      return;
    }
    locationModelRef?.current?.irrModalOpen(value);
  };

  const handleMapSubmit = ({ location }: any) => {
    const { afterSetLocation } = props;
    irrFormRef?.current?.setFieldsValue({
      location,
    });
    afterSetLocation && afterSetLocation(location);
    // eslint-disable-next-line
    locationModelRef?.current?.irrModalClose &&
      locationModelRef?.current?.irrModalClose();
  };

  return (
    <>
      <Form
        name="irr_form_action__warpper"
        ref={irrFormRef}
        onFinish={onFormSubmit}
        className={
          className
            ? `form_action__warpper ${className}`
            : `form_action__warpper`
        }
        autoComplete="off"
        colon={false}
        onValuesChange={curValuesChange}
        //@ts-ignore
        layout={layout}
        {...formOption}
      >
        <div className="form_action__containter">
          <div className="form_action__content" style={contentFormStyle}>
            <div className="extra">{children}</div>
            {formList.map((formItem, index) => {
              const {
                isShow = true,
                everyItemStyle = {},
                itemClass = '',
              } = formItem;
              return isShow ? (
                <div
                  key={index.toString()}
                  style={{ ...totolItemProps, ...everyItemStyle }}
                  className={`form_action-item form_action-item__${index} ${itemClass}`}
                >
                  {renderFormItem(formItem, index)}
                </div>
              ) : null;
            })}
          </div>
        </div>
        {!customFooter ? (
          <div
            style={queryAndReset.style}
            className={`form_action--btns ${queryAndReset.className}`}
          >
            {queryAndReset.queryVisible ? (
              <div className="form_btns--query">
                <Button type="primary" htmlType="submit">
                  {queryAndReset.queryText}
                </Button>
              </div>
            ) : null}
            {queryAndReset.resetVisible ? (
              <div className="form_btns--reset">
                <IrrButton
                  disabled={false}
                  bgColor={'#355587'}
                  // style={{ opacity: 0.8 }}
                  className={'form_reset--item'}
                  onClick={() => {
                    resetForm();
                    resetFormList && resetFormList();
                  }}
                >
                  {queryAndReset.resetText}
                </IrrButton>
              </div>
            ) : null}
          </div>
        ) : (
          <div className={`custom_btns`}>
            <div className="custom_btns--query">
              <Button
                type="primary"
                htmlType="submit"
                className="common-button action_opt__save"
              >
                保存
              </Button>
            </div>
            <span
              className="custom_btns__reback"
              onClick={() => {
                resetForm();
                resetFormList && resetFormList();
              }}
            >
              <RollbackOutlined />
              <span className="action_opt__text">返回</span>
            </span>
          </div>
        )}
      </Form>
      {/* <LocationModal
                ref={locationModelRef}
                onCancel={handleMapSubmit}
                data={props.currentRecord}
                mapOption={props.mapOption}
            /> */}
    </>
  );
};

export default forwardRef(IrrFormList);
